import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.*;

public class ExportAllTableSchemas {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/tworice_b2c";
        String username = "root";
        String password = "123456";

        String databaseName = "tworice_b2c";

        try {
            Connection connection = DriverManager.getConnection(url, username, password);

            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery("SHOW TABLES FROM " + databaseName);

            while (resultSet.next()) {
                String tableName = resultSet.getString(1);

                Statement innerStatement = connection.createStatement();  // 创建新的Statement
                ResultSet tableResult = innerStatement.executeQuery("SHOW CREATE TABLE " + databaseName + "." + tableName);

                if (tableResult.next()) {
                    String createTableSQL = tableResult.getString(2);
                    writeToFile(createTableSQL, tableName + "_schema.sql");
                    System.out.println("Table schema for " + tableName + " exported successfully.");
                }

                tableResult.close();
                innerStatement.close();  // 关闭内部Statement
            }

            resultSet.close();
            statement.close();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void writeToFile(String content, String filePath) {
        try {
            BufferedWriter writer = new BufferedWriter(new FileWriter(filePath));
            writer.write(content);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
